<template>
	<!-- 枚举管理 -->
	<div class="m-enumManager m-window">
		<!-- 页头 -->
		<div class="m-enum-pageHeader">
			<el-row :gutter="10">
				<el-form :inline-message="true" label-position="left">
					<el-col :span="8">
						<el-form-item label="编码/名称:" label-width="100px" class="rightItem">
							<el-input placeholder="输入编码或名称" v-model="searchForm.enum" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="2" :offset="4">
						<el-checkbox
							v-model="searchForm.state"
							true-label="1"
							false-label="0"
							@change="changeState"
						>显示停用</el-checkbox>
					</el-col>
					<el-col :span="2" >
						<el-button type="primary" @click="search(1,enumTypes)">查询</el-button>
					</el-col>
					<el-col :span="2">
						<el-button type="primary" @click="viewDetail">查看</el-button>
					</el-col>
					<el-col :span="2">
						<el-button type="primary" @click="addNewEnum">新增</el-button>
					</el-col>
					<el-col :span="2">
						<el-button type="primary" @click="editEnum" :disabled="searchForm.state==1">编辑</el-button>
					</el-col>
					<el-col :span="2">
						<el-button type="primary" @click="changeEnableState">{{searchForm.state==0?'停用':'启用'}}</el-button>
					</el-col>
				</el-form>
			</el-row>
		</div>
		<!-- 页面主体内容 -->
		<div class="m-enum-body">
			<div class="m-enum-left" v-loading="treeDataLoading">
				<el-tree
					class="filter-tree"
					:data="treeData"
					:props="defaultProps"
					:default-expanded-keys="['all']"
					node-key="enumCode"
					ref="tree"
					@node-click="treeNodeClick"
				></el-tree>
			</div>
			<div class="m-enum-right" v-loading="loading">
				<div class="m-agTable">
					<agGridComponents
						ref="agGridComponent"
						:getColumnDefs="columnDefs"
						:getRowSelection="'single'"
						:getGridOptions="gridOptions"
						:getRowData="rowData"
						:isColFit="true"
						v-loading="loading"
					></agGridComponents>
				</div>
				<div class="m-page">
					<el-pagination
						@size-change="handleSizeChange"
						@current-change="handleCurrentChange"
						:current-page="pageInfo.current"
						:page-sizes="[30,50,100,150,200]"
						:page-size="pageInfo.size"
						layout="total, sizes, prev, pager, next, jumper"
						:total="pageInfo.total"
					></el-pagination>
				</div>
			</div>
		</div>
		<!-- 新增/编辑弹窗 -->
		<enum-edit-dialog
			v-if="dialogVisible"
			:dialogVisible="dialogVisible"
			:title="dialogTitle"
			:ruleForm="ruleForm"
			:parentOption="parentOption"
			@closeDialog="goBackList"
			@beforeClose="dialogVisible=false"
		></enum-edit-dialog>
	</div>
</template>

<script>
import EnumEditDialog from "./common/enumEditDialog"
import Msg from "@/public/message"
import agGridComponents from '@/components/agGridComponents'
export default {
	data () {
		return {
			// 查询过滤条件
			searchForm: {
				enum: '',
				state: 0
			},
			//   编辑/新增表单
			ruleForm: {},
			//   树过滤值
			filterText: '',
			questionTitle: '',
			//   树数据
			treeData: [
				{
					enumName: '所有',
					enumCode: 'all',
					childs: []
				}
			],
			//   树数据加载
			treeDataLoading: false,
			//  树属性配置
			defaultProps: {
				children: 'childs',
				label: 'enumName'
			},
			//   分页相关
			pageInfo: {
				size: 30,
				current: 1,
				total: 0
			},
			columnDefs: [],
			gridOptions: {},
			rowData: [],
			loading: false,
			//  当前选中树节点及子节点code集合
			enumTypes: [],
			//  新增/编辑 弹窗相关
			dialogVisible: false,
			//   弹窗标题
			dialogTitle: '',
			//   上级集合
			parentOption: []
		}
	},
	props: {
		addTab: {
			type: Function
		}
	},
	methods: {
		filterNode (value, data) {
			if (!value) return true
			return data.enumName.indexOf(value) !== -1
		},
		// 查询列表数据
		search (flag, treeNode) {
			const { current, size } = this.pageInfo
			let params = {
				eqParams: {
					state: this.searchForm.state
				},
				likeParams: {
					enumCode: this.searchForm.enum,
					enumName: this.searchForm.enum,
				},
				inParams: {
					enumCode: treeNode
				},
				current: flag == 1 ? 1 : current,
				size
			}
			this.loading = true
			this.$http.getEnumList(params).then(({ data }) => {
				this.loading = false
				if (data.code == 1) {
					let rowData = data.rows
					this.$refs['agGridComponent'].gridOptions.api.setRowData(rowData)
					this.pageInfo.total = data.total
				} else {
					Msg.showErrorMsg(data.info)
				}
			}).catch(err => {
				this.loading = false
				Msg.showErrorMsg(err.data.message)
			})
		},
		// 每页显示条数改变回调
		handleSizeChange (val) {
			this.pageInfo.size = val
			this.search(1)
		},
		// 页码改变
		handleCurrentChange (val) {
			this.pageInfo.current = val
			this.search()
		},
		// 点击树节点回调
		treeNodeClick (treeItem, node) {
			this.enumTypes = []
			if (treeItem.enumCode == 'all') {
				this.search(1, [])
				return
			} else {
				foreachChilds(treeItem, this.enumTypes)
			}
			function foreachChilds (arr, typeCodes) {
				const { childs } = arr
				if (Array.isArray(childs) && childs.length > 0) {
					childs.forEach(item => {
						typeCodes.push(item.enumCode)
						foreachChilds(item, typeCodes)
					})
				}
			}
			this.enumTypes.push(treeItem.enumCode)
			this.search(1, this.enumTypes)
		},
		// 获取问题类型树
		getTreeData () {
			this.treeDataLoading = true
			this.$http.getQuestionTypeTree({ enumCode: '' }).then(({ data }) => {
				this.treeDataLoading = false
				if (data.code == 1) {
					this.treeData[0].childs = data.rows
					this.parentOption = data.rows
					setCodes(this.parentOption)
					// 递归设置节点属性
					function setCodes (arr) {
						arr.forEach(item => {
							if (item.isLeaf == 0) {
								item.disabled = true
							} else {
								item.disabled = false
							}
							if (Array.isArray(item.childs)) {
								if (item.childs.length > 0) {
									setCodes(item.childs)
								} else {
									item.childs = null
								}
							} else {
								item.childs = null
							}
						})
					}
				} else {
					Msg.showErrorMsg(data.info)
				}
			}).catch(err => {
				this.treeDataLoading = false
				Msg.showErrorMsg(err.data.message)
			})
		},
		// 新增问题
		addNewEnum () {
			this.ruleForm = {
				enumCode: '',
				enumName: '',
				isLeaf: 0,
				parentCode: '',
				sort: '',
				remark: '',
				state: 0
			}
			this.dialogTitle = "新增"
			this.dialogVisible = true
		},
		// 编辑问题
		editEnum () {
			let row = this.$refs.agGridComponent.gridOptions.api.getSelectedRows()
			if (row.length <= 0) {
				this.$alert("提示：请选择需要查看的数据", {
					showClose: false,
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				})
				return
			} else if (row.length > 1) {
				this.$alert("提示：每次只能查看一条数据！", {
					showClose: false,
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				})
				return
			}
			const { enumCode, enumName, id, state, isLeaf, sort, remark, parentCode } = row[0]
			this.ruleForm = {
				enumCode,
				enumName,
				id,
				state,
				isLeaf,
				sort,
				remark,
				parentCode
			}
			this.dialogTitle = "编辑"
			this.dialogVisible = true
		},
		// 查看问题详情
		viewDetail () {
			let row = this.$refs.agGridComponent.gridOptions.api.getSelectedRows()
			if (row.length <= 0) {
				this.$alert("提示：请选择需要查看的数据", {
					showClose: false,
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				})
				return
			} else if (row.length > 1) {
				this.$alert("提示：每次只能查看一条数据！", {
					showClose: false,
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				})
				return
			}
			const { enumCode, enumName, isLeaf, sort, remark, parentCode } = row[0]
			this.ruleForm = {
				enumCode,
				enumName,
				isLeaf: isLeaf == 1 ? '否' : '是',
				sort,
				remark,
				parentCode
			}
			this.dialogTitle = "查看"
			this.dialogVisible = true
		},
		// 停用/启用数据
		changeEnableState () {
			let row = this.$refs.agGridComponent.gridOptions.api.getSelectedRows()
			const { state } = this.searchForm
			let text = state == 0 ? '停用' : '启用'
			if (row.length <= 0) {
				this.$alert(`提示：请选择需要${text}的数据`, {
					showClose: false,
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				})
				return
			}
			this.$confirm(`是否${text}该公告？`, "消息提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				distinguishCancelAndClose: true
			}).then(_ => {
				let enumIds = row.map(item => {
					return item.id
				})
				let params = {
					ids: enumIds,
					state: state == 0 ? 1 : 0,
					modifyerId: this.$global.user.id,
					modifyer: this.$global.user.employeeName
				}
				this.$http.enableEnum(params).then(({ data }) => {
					if (data.code == 1) {
						Msg.showSuccessMsg(`${text}成功`)
						this.search(1)
					} else {
						Msg.showErrorMsg(data.info)
					}
				}).catch(err => {
					Msg.showErrorMsg(err.data.message)
				})
			})
		},
		// 返回
		goBackList (type) {
			if (type) {
				if (type == "add") {
					this.dialogVisible = false
					this.enumTypes = []
					this.getTreeData()
					this.search(1, this.enumTypes)
				} else if (type == "continue") {
					this.ruleForm = {
						enumCode: '',
						enumName: '',
						isLeaf: 0,
						parentCode: '',
						sort: '',
						remark: '',
						state: 0
					}
					this.enumTypes = []
					this.getTreeData()
					this.search(1, this.enumTypes)
				} else if (type == 'edit') {
					this.dialogVisible = false
					this.getTreeData()
					this.search(1, this.enumTypes)
				}
			} else {
				this.dialogVisible = false
			}
		},
		// 显示停用或启用
		changeState (val) {
			console.log(val)
			this.search(1, this.enumTypes)
		}
	},
	mounted () {
		this.getTreeData()
		this.search(1, this.enumTypes)
	},
	watch: {
		filterText (val) {
			this.$refs.tree.filter(val);
		}
	},
	components: {
		EnumEditDialog,
		agGridComponents
	},
	beforeMount () {
		this.columnDefs = [
			{ headerName: "", field: "", width: 60, checkboxSelection: true, headerCheckboxSelection: true },
			{ headerName: "上级编码", field: "parentCode", width: 120, tooltipField: 'parentCode' },
			{ headerName: "枚举编码", field: "enumCode", width: 120, tooltipField: 'enumCode' },
			{ headerName: "枚举名称", field: "enumName", width: 120, tooltipField: 'enumName' },
			{ headerName: "排序码", field: "sort", width: 110 },
			{ headerName: "备注", field: "remark", width: 110, tooltipField: 'remark' },
			{
				headerName: "状态",
				width: 100,
				field: "state",
				cellRenderer: function (params) {
					if (params.value == 0)
						return '<span class="ag-icon">启用</span>'
					else if (params.value == 1)
						return '<span class="ag-icon">停用</span>'
				}
			}];
	}
}
</script>
<style lang="less" scoped>
.m-enumManager {
	.m-enum-pageHeader {
		.el-form {
			.el-form-item {
				margin-bottom: 15px;
			}
		}
		.el-col-2 {
			min-width: 60px;
		}
	}
	.m-enum-body {
		position: absolute;
		top: 50px;
		left: 0;
		right: 0;
		bottom: 0;
		display: flex;
		.m-enum-left {
			width: 300px;
			padding: 10px;
			border: 1px solid #dcdfe6;
		}
		.m-enum-right {
			flex: 1;
			margin-left: 10px;
			.m-agTable {
				height: ~"calc(100% - 34px)";
			}
		}
	}
}
</style>